import React, { useState, useEffect } from 'react';
import { Button, message, Modal, Tree, Space, Empty } from 'antd';
import { PlusOutlined, DeleteOutlined, FolderAddOutlined, EditOutlined, SaveOutlined } from '@ant-design/icons';
import { v4 as uuidv4 } from 'uuid';
import request from '@/utils/request';
import { useSearchParams } from 'react-router-dom';
import './DataManagement.css';
import CreateTemplateModal from '../components/PDSData/CreateTemplateModal';
import AddSubDirModal from '../components/PDSData/AddSubDirModal';
import EditNameModal from '../components/PDSData/EditNameModal';
import UploadContent from '../components/PDSData/UploadContent';
import DataContent from '../components/PDSData/DataContent';
import GenerateDatasetModal from '../components/PDSData/GenerateDatasetModal';
import TemplateListModal from '../components/PDSData/TemplateListModal';
import Breadcrumb from '../components/Breadcrumb';

interface TreeNode {
  title: string;
  key: string;
  children?: TreeNode[];
}

export interface DataType {
  key: string;
  file_name: string;
  size: number;
  upload_time: string;
  creator: string;
  task_type: string;
  payload: string;
  data_level: string;
  collect_start_time: string;
  collect_end_time: string;
}

const PDSData: React.FC = () => {
  const [searchParams] = useSearchParams();
  const datasetId = searchParams.get('id');
  const [selectedDatasetId, setSelectedDatasetId] = useState<number>(datasetId ? parseInt(datasetId) : 0);
  const [selectedTreeUuid, setSelectedTreeUuid] = useState<string>('');

  // 左侧树形目录mock
  const [treeData, setTreeData] = useState<TreeNode | null>(null);
  const [selectedTreeKey, setSelectedTreeKey] = useState<string | null>(null);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [newTemplateName, setNewTemplateName] = useState('');
  const [addSubDirModalVisible, setAddSubDirModalVisible] = useState(false);
  const [newSubDirName, setNewSubDirName] = useState('');
  const [selectedNodeKey, setSelectedNodeKey] = useState<string | null>(null);
  const [editNameModalVisible, setEditNameModalVisible] = useState(false);
  const [editingNode, setEditingNode] = useState<{ key: string; title: string } | null>(null);
  const [newNodeName, setNewNodeName] = useState('');
  const [showDataContent, setShowDataContent] = useState(false);
  const [generateModalVisible, setGenerateModalVisible] = useState(false);
  const [templateListVisible, setTemplateListVisible] = useState(false);

  // Helper to find a node by key
  const findNodeByKey = (key: string, nodes: TreeNode[]): TreeNode | null => {
    for (const node of nodes) {
      if (node.key === key) {
        return node;
      }
      if (node.children) {
        const found = findNodeByKey(key, node.children);
        if (found) {
          return found;
        }
      }
    }
    return null;
  };

  // 添加子目录
  const handleAddSubDir = (parentKey: string) => {
    setSelectedNodeKey(parentKey);
    setAddSubDirModalVisible(true);
  };

  // 递归查找并添加子目录，适配根节点为对象
  const addSubDirToTree = (node, parentKey, newDir) => {
    if (node.key === parentKey) {
      return {
        ...node,
        children: [...(node.children || []), newDir]
      };
    }
    if (node.children) {
      return {
        ...node,
        children: node.children.map((child) => addSubDirToTree(child, parentKey, newDir))
      };
    }
    return node;
  };

  // 判断是否为DATA目录
  const isDataDirectory = (title: string) => {
    return title === 'DATA';
  };

  // 判断是否为DATA目录或其子目录
  const isDataOrChildDirectory = (nodeKey: string, tree: TreeNode[]): boolean => {
    const checkDescendantOfData = (nodes: TreeNode[], targetKey: string, isUnderData: boolean): boolean => {
      for (const node of nodes) {
        const currentIsUnderData = isUnderData || node.title === 'DATA';

        if (node.key === targetKey) {
          return currentIsUnderData;
        }

        if (node.children && checkDescendantOfData(node.children, targetKey, currentIsUnderData)) {
          return true;
        }
      }
      return false;
    };

    return checkDescendantOfData(tree, nodeKey, false);
  };

  // 保存树形结构
  const saveTreeData = async (
    newTreeData: TreeNode[],
    actionType: 'create' | 'update' | 'delete' = 'update',
    treeUuid?: string
  ) => {
    try {
      const response = await request('/PDS/DataSetTemplateSave', {
        method: 'POST',
        data: {
          dataset_id: selectedDatasetId,
          action_type: actionType,
          tree_uuid: treeUuid,
          tree: newTreeData
        }
      });
      if (response.data.code === 200) {
        // message.success('保存成功');
      } else {
        message.error(response.data.msg || '保存失败');
      }
    } catch (error) {
      console.error('保存PDS模版失败:', error);
      message.error(error instanceof Error ? error.message : '保存失败');
    }
  };

  // 修改创建模版的处理函数，直接覆盖根节点
  const handleCreateTemplate = async (name) => {
    const newKey = uuidv4();
    const newTreeData = {
      title: name,
      key: newKey,
      children: [
        {
          title: 'DATA',
          key: uuidv4(),
          children: []
        }
      ]
    };
    setTreeData(newTreeData);
    // 展开所有节点
    const getAllKeys = (node) => {
      let keys = [node.key];
      if (Array.isArray(node.children)) {
        node.children.forEach((child) => {
          keys = keys.concat(getAllKeys(child));
        });
      }
      return keys;
    };
    setExpandedKeys(getAllKeys(newTreeData));
    await saveTreeData([newTreeData], 'create', newKey); // 兼容老接口，传数组
    setCreateModalVisible(false);
    message.success('模版创建成功');
  };

  // 修改添加子目录的处理函数，适配根节点为对象
  const handleAddSubDirConfirm = async (name: string) => {
    const newKey = uuidv4();
    const newTreeData = addSubDirToTree(treeData, selectedNodeKey, {
      title: name,
      key: newKey,
      children: []
    });
    setTreeData(newTreeData);
    await saveTreeData([newTreeData], 'update');
    setAddSubDirModalVisible(false);
    message.success('子目录添加成功');
  };

  // 修改删除节点的处理函数
  const handleDeleteNodeConfirm = async (key: string) => {
    // 支持对象和数组
    const deleteNodeFromTree = (tree, targetKey) => {
      if (Array.isArray(tree)) {
        return tree.map((node) => deleteNodeFromTree(node, targetKey)).filter(Boolean);
      }
      if (tree.key === targetKey) {
        return null;
      }
      if (tree.children) {
        const newChildren = deleteNodeFromTree(tree.children, targetKey);
        return { ...tree, children: newChildren };
      }
      return tree;
    };

    // 包一层数组处理，最后还原为对象
    const result = deleteNodeFromTree([treeData], key);
    const newTreeData = Array.isArray(result) && result.length > 0 ? result[0] : null;
    setTreeData(newTreeData);
    await saveTreeData(newTreeData ? [newTreeData] : [], 'delete', key);
    message.success('删除成功');
  };

  // 修改编辑名称的处理函数
  const handleEditName = async (key, newName) => {
    // 支持对象和数组
    const updateNodeTitle = (tree, targetKey, newTitle) => {
      if (Array.isArray(tree)) {
        return tree.map((node) => updateNodeTitle(node, targetKey, newTitle));
      }
      if (tree.key === targetKey) {
        return { ...tree, title: newTitle };
      }
      if (tree.children) {
        return { ...tree, children: updateNodeTitle(tree.children, targetKey, newTitle) };
      }
      return tree;
    };

    const newTreeData = updateNodeTitle(treeData, key, newName);
    setTreeData(newTreeData);
    await saveTreeData([newTreeData], 'update');
    setEditNameModalVisible(false);
    setEditingNode(null);
    message.success('修改成功');
  };

  // 开始编辑
  const startEdit = (key: string, title: string) => {
    setEditingNode({ key, title });
    setNewNodeName(title);
    setEditNameModalVisible(true);
  };

  // 获取树形数据，适配根节点结构
  const fetchTreeData = async (datasetId: number) => {
    try {
      const response = await request(`/PDS/DataSetTemplateSearch?dataset_id=${datasetId}`, {
        method: 'GET'
      });
      if (response.data.code === 200) {
        const newTreeData = response.data.data;
        if (Array.isArray(newTreeData)) {
          if (newTreeData.length > 0) {
            setTreeData(newTreeData[0] || null);
            // 获取所有节点的key并设置为展开状态
            const getAllKeys = (nodes: TreeNode[]): string[] => {
              return nodes.reduce((keys: string[], node) => {
                keys.push(node.key);
                if (node.children) {
                  keys.push(...getAllKeys(node.children));
                }
                return keys;
              }, []);
            };
            setExpandedKeys(getAllKeys([newTreeData[0]]));
          } else {
            // 如果没有数据，创建默认模版
            const defaultTreeData = {
              title: '模版',
              key: uuidv4(),
              children: [
                {
                  title: 'DATA',
                  key: uuidv4(),
                  children: []
                }
              ]
            };
            setTreeData(defaultTreeData);
            setExpandedKeys([defaultTreeData.key, defaultTreeData.children[0].key]);
            // 保存默认模版到后端
            await saveTreeData([defaultTreeData], 'create', defaultTreeData.key);
          }
        } else if (typeof newTreeData === 'object' && newTreeData !== null) {
          setTreeData(newTreeData);
          const getAllKeys = (nodes: TreeNode[]): string[] => {
            return nodes.reduce((keys: string[], node) => {
              keys.push(node.key);
              if (node.children) {
                keys.push(...getAllKeys(node.children));
              }
              return keys;
            }, []);
          };
          setExpandedKeys(getAllKeys([newTreeData]));
        } else {
          // 如果没有数据，创建默认模版
          const defaultTreeData = {
            title: '模版',
            key: uuidv4(),
            children: [
              {
                title: 'DATA',
                key: uuidv4(),
                children: []
              }
            ]
          };
          setTreeData(defaultTreeData);
          setExpandedKeys([defaultTreeData.key, defaultTreeData.children[0].key]);
          // 保存默认模版到后端
          await saveTreeData([defaultTreeData], 'create', defaultTreeData.key);
        }
      } else {
        message.error(response.data.msg || '获取模版数据失败');
      }
    } catch (error) {
      console.error('获取PDS模版数据失败:', error);
      message.error(error instanceof Error ? error.message : '获取模版数据失败');
    }
  };

  // 在组件加载时获取数据
  useEffect(() => {
    if (selectedDatasetId) {
      fetchTreeData(selectedDatasetId);
    }
  }, [selectedDatasetId]);

  // 保存模版到新接口
  const handleSaveTemplate = async (templateNode) => {
    try {
      const response = await request('/PDS/DataSetTemplateSaveNew', {
        method: 'POST',
        data: {
          template_name: templateNode.title,
          template_json: templateNode
        }
      });
      if (response.data.code === 200) {
        message.success('模版保存成功');
      } else {
        message.error(response.data.msg || '模版保存失败');
      }
    } catch (error) {
      console.error('保存模版失败:', error);
      message.error(error instanceof Error ? error.message : '模版保存失败');
    }
  };

  // 弹窗确认删除
  const confirmDeleteNode = (key: string) => {
    Modal.confirm({
      title: '确认删除该目录吗？',
      content: '删除后该目录下的所有内容也会被删除，且无法恢复。',
      okText: '确定',
      cancelText: '取消',
      onOk: () => handleDeleteNodeConfirm(key)
    });
  };

  return (
    <div className="data-management-container">
      <Breadcrumb text="数据检索 / PDS数据集服务" />
      <div className="data-management-page" style={{ top: 50, display: 'flex', width: '100%', minWidth: '1200px' }}>
        {/* 左侧树形目录 */}
        <div className="data-management-left" style={{ width: '350px', flexShrink: 0, marginRight: '16px' }}>
          <div className="data-management-left-content">
            <div style={{ display: 'flex', gap: 16, marginBottom: 12 }}>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                style={{ marginRight: 8 }}
                onClick={() => setCreateModalVisible(true)}
              >
                创建新模版
              </Button>
              <Button onClick={() => setTemplateListVisible(true)}>模版列表</Button>
            </div>
            <div className="data-management-tree-container">
              {!treeData ? (
                <Empty description="暂无数据" />
              ) : (
                <>
                  <Tree
                    treeData={[treeData]}
                    expandedKeys={expandedKeys}
                    onExpand={(keys) => setExpandedKeys(keys)}
                    selectedKeys={selectedTreeKey ? [selectedTreeKey] : []}
                    onSelect={(keys: React.Key[]) => {
                      const selectedKey = keys[0] as string;
                      setSelectedTreeKey(selectedKey);
                      setSelectedTreeUuid(selectedKey);
                      // 检查选中的节点是否是DATA目录或其子目录
                      const isDataNodeSelected = isDataOrChildDirectory(selectedKey, [treeData]);
                      setShowDataContent(isDataNodeSelected);
                    }}
                    titleRender={(nodeData: TreeNode) => {
                      // 判断是否为根节点
                      const isRoot = treeData && nodeData.key === treeData.key;
                      return (
                        <div
                          style={{
                            display: 'flex',
                            justifyContent: 'space-between',
                            alignItems: 'center',
                            width: '100%'
                          }}
                        >
                          <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', flex: 1 }}>
                            {nodeData.title}
                          </span>
                          <Space size={0} style={{ marginLeft: 5 }}>
                            {!isDataDirectory(nodeData.title) && (
                              <Button
                                type="text"
                                size="small"
                                icon={<EditOutlined />}
                                onClick={(e) => {
                                  e.stopPropagation();
                                  startEdit(nodeData.key, nodeData.title);
                                }}
                              />
                            )}
                            <Button
                              type="text"
                              size="small"
                              icon={<FolderAddOutlined />}
                              onClick={(e) => {
                                e.stopPropagation();
                                handleAddSubDir(nodeData.key);
                              }}
                            />
                            {!isDataDirectory(nodeData.title) && !isRoot && (
                              <Button
                                type="text"
                                size="small"
                                danger
                                icon={<DeleteOutlined />}
                                onClick={(e) => {
                                  e.stopPropagation();
                                  confirmDeleteNode(nodeData.key);
                                }}
                              />
                            )}
                            {isRoot && (
                              <Button
                                type="text"
                                size="small"
                                icon={<SaveOutlined />}
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleSaveTemplate(treeData);
                                }}
                              >
                                保存模版
                              </Button>
                            )}
                          </Space>
                        </div>
                      );
                    }}
                  />
                </>
              )}
            </div>
            <Button type="primary" block style={{ marginTop: 16 }} onClick={() => setGenerateModalVisible(true)}>
              生成数据集
            </Button>
          </div>
        </div>
        {/* 右侧主内容区 */}
        {selectedTreeKey ? (
          showDataContent ? (
            <DataContent datasetId={selectedDatasetId} treeUuid={selectedTreeUuid} />
          ) : (
            <UploadContent datasetId={selectedDatasetId} treeUuid={selectedTreeUuid} />
          )
        ) : (
          <div
            style={{
              flex: 1,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: 18,
              color: '#999',
              background: 'white'
            }}
          >
            请先选择左侧目录
          </div>
        )}
      </div>
      <CreateTemplateModal
        visible={createModalVisible}
        onCancel={() => setCreateModalVisible(false)}
        onOk={handleCreateTemplate}
      />

      <AddSubDirModal
        visible={addSubDirModalVisible}
        onCancel={() => setAddSubDirModalVisible(false)}
        onOk={handleAddSubDirConfirm}
      />

      <EditNameModal
        visible={editNameModalVisible}
        onCancel={() => {
          setEditNameModalVisible(false);
          setEditingNode(null);
        }}
        onOk={(name) => editingNode && handleEditName(editingNode.key, name)}
        initialName={editingNode?.title || ''}
      />

      <GenerateDatasetModal
        visible={generateModalVisible}
        onCancel={() => setGenerateModalVisible(false)}
        onOk={() => setGenerateModalVisible(false)}
        datasetId={selectedDatasetId}
      />

      <TemplateListModal
        visible={templateListVisible}
        onCancel={() => setTemplateListVisible(false)}
        onSelect={(template) => {
          if (template && template.template_json) {
            // 递归为每个节点生成新key
            const assignNewKeys = (node) => {
              const newNode = { ...node, key: uuidv4() };
              if (Array.isArray(newNode.children) && newNode.children.length > 0) {
                newNode.children = newNode.children.map(assignNewKeys);
              }
              return newNode;
            };
            const newTree = assignNewKeys(template.template_json);
            // 递归获取所有key
            const getAllKeys = (node) => {
              let keys = [node.key];
              if (Array.isArray(node.children)) {
                node.children.forEach((child) => {
                  keys = keys.concat(getAllKeys(child));
                });
              }
              return keys;
            };
            setTreeData(newTree);
            setExpandedKeys(getAllKeys(newTree));
            setSelectedTreeKey(null);
            setSelectedTreeUuid('');
            setShowDataContent(false);
            // 判断有无老tree的key，决定用delete还是create
            if (treeData && treeData.key) {
              saveTreeData([newTree], 'delete', treeData.key).then(() => {
                message.success('已应用所选模版');
              });
            } else {
              saveTreeData([newTree], 'create', newTree.key).then(() => {
                message.success('已应用所选模版');
              });
            }
          }
        }}
      />
    </div>
  );
};

export default PDSData;
